/*
 * @Description:
 * @Author: xuzp4
 * @Date: 2022-01-18 15:33:34
 * @LastEditors: xuzp4
 * @LastEditTime: 2022-01-19 10:41:15
 * @FilePath: \vue_demo\src\service\index2.js
 */

const AWS = require("aws-sdk");
const uploads = require("@mapbox/mapbox-sdk/services/uploads");
const fs = require("fs");
const express = require("express");
const multer = require('multer')
var app = express();
const upload = multer({ dest: "upload/" }).any();
app.all("*", function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  res.header("Access-Control-Allow-Methods", "*");
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});
app.post("/upload", function(req, res) {
  upload(req, res, function(err) {
    req.file = req.files[0];
    const path = req.file.path;
    const uploadsClient = uploads({
      accessToken:
        "sk.eyJ1IjoieHUwNDMwIiwiYSI6ImNreWpzanpvcjB3NjIybnFvdjQ3eGoxZ24ifQ.fv-c0afyBoOEB19zgdGclQ"
    });

    const getCredentials = () => {
      return uploadsClient
        .createUploadCredentials()
        .send()
        .then(response => {
          console.log("getCredentials", response);
          return response.body;
        });
    };
    const putFileOnS3 = credentials => {
      const s3 = new AWS.S3({
        accessKeyId: credentials.accessKeyId,
        secretAccessKey: credentials.secretAccessKey,
        sessionToken: credentials.sessionToken,
        region: "us-east-1"
      });
      return s3
        .putObject({
          Bucket: credentials.bucket,
          Key: credentials.key,
          Body: fs.createReadStream(path) 
        })
        .promise();
    };
    let creds = {};
    getCredentials()
      .then(credentials => {
        creds = credentials;
        return putFileOnS3(credentials);
      })
      .then(credentials => {
        console.log("credentials", creds);
        return uploadsClient
          .createUpload({
            tileset: `xu0430.aaa`,
            url: creds.url,
            name: "aaa"
          })
          .send();
      })
      .then(() => console.log("created Mapbox upload"), res.send("success"),res.end())
      .catch(err => console.log("error:", err));
  
  });
});
app.listen(3000);
